<template>
  <div>
    <div>
      <ele-page
        v-loading="loading"
        :formConfig="formConfig"
        ref="eleTable"
        :operateList="operateList"
        @handleOperateEvent="handleOperateEvent"
        :column="column"
        :getList="getList"
        uniqueId="roleTable"
      >
      </ele-page>
    </div>
    <ele-form-drawer
      class="dialog-pack"
      :isLoading="isLoading"
      v-model="formDataDialog"
      v-bind="type ? sourcesDialogre : formDescDialogUp"
      :request-fn="handleSubmit"
      :visible.sync="visible"
      :title="title"
    >
    </ele-form-drawer>
  </div>
</template>

<script>
import {
  operateList,
  formConfig,
  formDescDialogUp,
  rowConfig,
  sourcesDialogre,
} from "./config";
import {
  getList,
  rowCreate,
  rowUpdate,
  rowDel,
  setResource,
  getResource,
  getTreeList,
} from "@/api/role";

import { resourceWithBs } from "@/api/common.js";
import { getUserD } from "@/api/userInfo.js";
let diReeList = [];
let aciveList = [];
export default {
  name: "role",
  data() {
    return {
      type: 0, //1:分配资源 0:修改
      title: null,
      isAdmin: false, //是否是超级管理员, init角色
      visible: false,
      isLoading: false,
      loading: false,

      formDataDialog: {},
      formDescDialogUp, //新增修改框
      sourcesDialogre, //分配资源
      formConfig,
      operateList,
      getList,
      column: [
        {
          type: "index",
          label: this.$t("common.order"),
          width: 60,
        },
        {
          prop: "roleCode",
          label: this.$t("role.roleCode"),
          minWidth: 130,
        },
        {
          prop: "roleName",
          label: this.$t("role.roleName"),
          minWidth: 130,
        },

        //无用，隐藏
        // {
        //   prop: "roleSort",
        //   label: this.$t("role.roleSort"),
        //   minWidth: 130
        // },
        {
          prop: "status",
          label: this.$t("user.status"),

          render: (h, { row }) => {
            return (
              <el-switch
                onChange={() => this.handleSwitch(row)}
                v-model={row.status}
                active-value={"0"}
                inactive-value={"1"}
                active-color="#13ce66"
                inactive-color="#ff4949"
              ></el-switch>
            );
          },
        },
        {
          prop: "createTime",
          label: this.$t("common.createTime"),
          width: 180,
        },
        {
          prop: "operate",
          label: this.$t("common.operation"),
          minWidth: 140,
          render: (h, scope) => {
            return (
              <ele-row-operation
                scope={scope}
                rowConfig={rowConfig}
                onRowOperate={this.rowOperate}
              ></ele-row-operation>
            );
          },
        },
      ],
    };
  },
  computed: {
    formDesc() {
      return this.type ? sourcesDialogre : formDescDialogUp;
    },
  },
  methods: {
    async getUserD() {
      let res = await getUserD();
      this.isAdmin = (res.data.result.roles || []).some(
        (ite) => ite.code === "init"
      );
    },

    //表格顶部按钮操作事件
    handleOperateEvent(data) {
      this.title = data.name;
      const fnc = {
        add: () => {
          this.type = 0;
          this.formDataDialog = {};
          this.visible = true;
        },
      };
      fnc[data.handleName]();
    },
    //改变状态
    handleSwitch(data) {
      this.rowUpdate(data);
    },
    //表格行操作事件
    rowOperate({ handleName, name, row }) {
      console.log(row);
      this.title = name;
      const fnc = {
        add: () => {
          this.formDataDialog = {
            parentId: row.id,
          };
          this.visible = true;
        },
        edit: () => {
          this.type = 0;
          let { roleCode, roleName, roleSort, status, roleId } = row;

          this.formDataDialog = {
            roleCode,
            roleName,
            roleSort,
            status,
            roleId,
          };
          this.visible = true;
        },
        resources: async () => {
          this.type = 1;
          let { roleCode, roleName, roleId } = row;

          if (roleCode == "init") {
            this.$set(
              this.sourcesDialogre.formDesc.resourceIds,
              "options",
              diReeList
            );
          } else {
            this.$set(
              this.sourcesDialogre.formDesc.resourceIds,
              "options",
              aciveList
            );
          }
          let { data } = await getResource(roleId);

          this.formDataDialog = {
            roleCode,
            roleName,
            roleId,
            resourceIds: [...data.result],
          };
          this.visible = true;
        },
        delete: () => {
          this.$confirm(
            this.$t("common.deleteSingle"),
            this.$i18n.t("common.tip"),
            {
              confirmButtonText: this.$i18n.t("common.ok"),
              cancelButtonText: this.$i18n.t("common.cancel"),
              type: "warning",
            }
          ).then(() => {
            this.rowDel(row.roleId);
          });
        },
      };
      fnc[handleName]();
    },

    //弹框提交事件
    handleSubmit(data) {
      if (this.isLoading) return; // 判断状态
      this.isLoading = true;
      if (!this.type) {
        this.formDataDialog.roleId
          ? this.rowUpdate(data)
          : this.rowCreate(data);
      } else {
        this.setResource(data);
      }
    },
    //新增
    rowCreate(data) {
      rowCreate(data)
        .then((res) => {
          this.$message.success(
            res.data.message || this.$i18n.t("common.addSuccess")
          );
          this.visible = false;
          this.refresh();
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    //修改
    rowUpdate(data) {
      rowUpdate(data)
        .then((res) => {
          this.$message.success(
            res.data.message || this.$i18n.t("common.editSuccess")
          );

          this.visible = false;
          this.refresh();
        })
        .finally(() => {
          this.isLoading = false;
        });
    }, //分配资源
    setResource(data) {
      let { roleId, resourceIds } = data;
      setResource({ roleId, resourceIds: resourceIds.join() })
        .then((res) => {
          this.$message.success(this.$t("common.resourceUpdatedSuccessfully"));
          this.visible = false;

          if (data.roleCode == "init") {
            this.init();
          }
          this.refresh();
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    //删除
    rowDel(data) {
      this.loading = true;
      rowDel(data)
        .then((res) => {
          this.$message.success(this.$t("common.deleteSuccess"));
          this.refresh();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    //刷新表格数据
    refresh(isReset = true) {
      this.$refs.eleTable.refresh(isReset);
    },

    //拉伸树形结构数组数据为一维数组，方便比对
    readNodes(nodes = [], arr = []) {
      for (let item of nodes) {
        arr.push(item);
        if (item.children && item.children.length) {
          this.readNodes(item.children, arr);
        }
      }
      return arr;
    },

    clone(list) {
      var temp = {};
      list.map((item) => {
        if (item.children && item.children.length) {
          clone(o[i]);
        } else {
          if (allList.some((ite) => ite.id == item.id)) {
            item.isDisabled = false;
          } else {
            item.isDisabled = true;
          }
        }
      });
      return list;
    },

    _arrRoutes(menus, all) {
      const list = [];
      all.filter((item) =>
        all.some((ele) => {
          if (item.children && item.children.length) {
            const routeChild = this._arrRoutes(
              ele.children ?? [],
              item.children ?? []
            );
            if (routeChild.length) item.children = routeChild;
          }
          // 筛选条件
          if (item.id == ele.id && ["F", "C"].includes(item.type)) {
            item.isDisabled = false;
            //   list.push(item);
          } else {
            if (["F", "C"].includes(item.type)) {
              item.isDisabled = true;
            } else {
              item.isDisabled = false;
            }
          }
        })
      );
      return all;
    },

    async init() {
      this.getUserD();
      let res = await getTreeList();
      diReeList = JSON.parse(JSON.stringify(res.data.result));

      let { tenantCode, userId } = this.$store.getters.userInfo;

      let res1 = await resourceWithBs({
        tenantCode,
        userId,
      });
      let allList = this.readNodes(res1.data.result);
      // console.log(999, this.$store.getters.menus);

      function resolveTreeData(treeData) {
        const tree = treeData.map((item) => {
          if (allList.some((ite) => ite.id == item.id)) {
            item.isDisabled = false;
          } else {
            //   if (item.type == "F") {
            //   item.isDisabled = false;
            // } else {
            item.isDisabled = true;
            // }
          }
          if (Object.prototype.hasOwnProperty.call(item, "children")) {
            item.children && resolveTreeData(item.children);
          }
          return item;
        });
        return tree;
      }
      let list = resolveTreeData(res.data.result);
      aciveList = list;
      this.$set(this.sourcesDialogre.formDesc.resourceIds, "options", list);
    },
  },
  created() {
    this.init();
  },
};
</script>
<style lang="scss" scoped>
.dialog-pack {
  // // tree多选 input框隐藏
  // /deep/.vue-treeselect__control {
  //   display: none;
  // }
  // // bug默认展开时,提交按钮被覆盖-->取消定位
  // /deep/.vue-treeselect__menu-container {
  //   position: static;
  // }
  // /deep/.vue-treeselect__menu {
  //   position: static;
  // }
}
</style>
